<?php
/**
 * Created by PhpStorm.
 * Script Name: CheckAuth.php
 * Create: 2022/9/19 19:15
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace app\tenant\middleware;

use app\common\service\Tenant;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class CheckInfo implements MiddlewareInterface
{
    /**
     * @var string
     */
    private $action;
    /**
     * @var string
     */
    private $controller;
    private $adminInfo;

    /**
     * @inheritDoc
     */
    public function process(Request $request, callable $handler): Response
    {
        $app        = request()->getApp();
        $controller = request()->getController();
        $this->action     = request()->getAction();
        $controller_layer = explode('/', $controller);
        $this->controller = strtolower($controller_layer[count($controller_layer) - 1]);
        $this->adminInfo = Tenant::sessionTenantInfo();
        if(($res = $this->checkMobile()) !== true){
            return $res;
        }
        return $handler($request);
    }

    /**
     * 验证手机号是否完善
     * Author: fudaoji<fdj@kuryun.cn>
     */
    private function checkMobile(){
        if(\request()->isGet() && !$this->ignoreRoute() && dao_config('system.site.need_mobile') && empty($this->adminInfo['mobile'])){
            return error('请先完成手机号绑定', url('tenant/account'));
        }
        return true;
    }

    private function ignoreRoute(){
        $white_controller = ['auth', 'index'];
        $white_route = ['tenant/account'];
        $node = strtolower($this->controller.'/'.$this->action);
        if(in_array($this->controller, $white_controller) || in_array($node, $white_route)){
            return true;
        }
        return false;
    }
}